//
//  PlayerManager.m
//  MusicPlayer-two
//
//  Created by lanou3g on 15/8/22.
//  Copyright (c) 2015年 大展宏图. All rights reserved.
//
#define  HJLog(...) NSLog(__VA_ARGS__)
#import "PlayerManager.h"
#import "URLs.h"
#import "MusicInfo.h"

@import AVFoundation;

@interface PlayerManager ()

@property (nonatomic, strong) AVPlayer *musicPlayer;
@property (nonatomic, assign) NSInteger parperIndex;
@property (nonatomic, strong) NSTimer *timer;

@end
@implementation PlayerManager

static PlayerManager * s_defaultManager = nil;


+ (instancetype)defaultManager{
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_defaultManager = [[self alloc]init];
    });
    return s_defaultManager;
}

- (instancetype)init{
    
    self = [super init];
    if (self) {
        self.playlist = [NSMutableArray new];
        
        self.playMode = PlayModeByLoop;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didMusicPlayFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    }
    return self;
}

- (void)didMusicPlayFinished{

    [self playNextMusic];
    [self.musicPlayer play];

}


- (void)getPlayerlistComplete:(void (^)())complete{
    
   dispatch_async(dispatch_queue_create(0, 0), ^{
       NSArray *arry = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:KPlaylist]];
//       HJLog(@"%@",arry);
       for (NSDictionary *dic in arry) {
           MusicInfo *musicInfo = [MusicInfo musicInfoSetValuesForKeysWithDictionary:dic];
           [self.playlist addObject:musicInfo];
       }
       dispatch_async(dispatch_get_main_queue(), ^{
           if (complete) {
               complete();
           }
       });
       
       
   });

}

- (void)parpreNextMuesicWihtIndex:(NSInteger )index{
  
    if (self.parperIndex != index) {
        self.parperIndex = index;
        self.currentMusic = self.playlist[index];
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[self.currentMusic mp3Url]]];
        [self.musicPlayer replaceCurrentItemWithPlayerItem:playerItem];
        
    }

}


- (void)musicPlay{
    
   
    
     [self.musicPlayer play];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(timerAction) userInfo:nil repeats:true];

}

- (void)timerAction{

    if (self.delegate && [self.delegate respondsToSelector:@selector(musicPlayingWithCurrentSeconds:)]) {
        
        [self.delegate musicPlayingWithCurrentSeconds:CMTimeGetSeconds(self.musicPlayer.currentTime)];
    }
    


}

/**
 *  上一首
 */
- (void)playLastMusic{
    
    if (self.parperIndex <= 0) {
        [self setToTimeByValue:0];
    }else {
    [self parpreNextMuesicWihtIndex:self.parperIndex - 1];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didCutMusicComplete)]) {
        
        [self.delegate didCutMusicComplete];
    }
    
}


/**
 *  下一首
 */
- (void)playNextMusic{

//    [self parpreNextMuesicWihtIndex:self.parperIndex + 1 == self.playlist.count ? 0 : self.parperIndex + 1];
    switch (self.playMode) {
        case PlayModeByLoop:
        {
            [self parpreNextMuesicWihtIndex:self.parperIndex + 1 == self.playlist.count ? 0 : self.parperIndex + 1];
        
        }
            break;
        case PlayModeByRandom:
        {
            [self parpreNextMuesicWihtIndex:arc4random() % self.playlist.count];
            
        }
            break;
        case PlayModeBySingle:
        {
            [self setToTimeByValue:0];
            
        }
            break;
            
        default:
            break;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didCutMusicComplete)]) {
        
        [self.delegate didCutMusicComplete];
    }
}


- (void)musicPause{

    [self.musicPlayer pause];
    
    [self.timer invalidate];
    self.timer = nil ;

}






// 关联播放器的音量....
- (void)musciChangeWithValumn:(float )valumn{

    self.musicPlayer.volume = valumn;

}

/**
 *  用Slider控制时间
 */
- (void)setToTimeByValue:(NSInteger )value{

    [self.musicPlayer seekToTime:CMTimeMake(value, 1)];

}


//AVplayer的懒加载

- (AVPlayer *)musicPlayer{

    if (!_musicPlayer) {
        _musicPlayer = [[AVPlayer alloc] init];
    }

    return _musicPlayer;
}

@end
